<?php 
	
	include_once("bin/connexion.php");
	
	if(isset($_SESSION["user_id"]))
	{
		$id = $_SESSION["user_id"];
		$query = "SELECT * FROM user where id='$id'";
		$result = mysqli_query($bdd,$query);
		$user = mysqli_fetch_array($result);
		$num_biens = 0;
		
		if($user["bailleur"] == 1)
		{
			$query = "SELECT * FROM bien where id_owner='$id'";
			$result = mysqli_query($bdd,$query);
			$num_biens = mysqli_num_rows($result);
		}
		
		$infos = array($user["nom"], $user["prenom"], $user["bailleur"], $user["pic"], $num_biens, $user["mail"], $user["password"]);
	}
	else
	{
		header("location: freebed-login.php");
	}
	
	//GOOGLE SEARCHING ENGINE ALGO v1337 !! COPYRIGHT NASA
	if(isset($_POST["envoyer"]))
	{
		$ville = $_POST["ville"];
		$surface = $_POST["surface"];
		$type = $_POST["type"];
		$prix = $_POST["prix"];
	
		//recup l'id de la ville choisis
		$query = "SELECT * FROM ville WHERE libelle='$ville'";
		$ret_ville = mysqli_query($bdd, $query);

		//la ville a été trouver
		if($ret_ville == true)
		{
			$ret_table = array();
			$i = 0;
			while($data = mysqli_fetch_array($ret_ville))
			{	
				//prend tous les bien selon la ville
				$query = "SELECT * FROM bien WHERE id_ville='$data[0]'";
				$ret_bien = mysqli_query($bdd, $query);
				
				//on a trouvé un bien dans la ville
				if($ret_bien == true)
				{
					//recup le type
					$query = "SELECT * FROM type_bien WHERE id='$type'";
					$ret_type_bien = mysqli_query($bdd, $query);
					$type_bien = mysqli_fetch_array($ret_type_bien);
					
					while($data2 = mysqli_fetch_array($ret_bien))
					{
						//on approxim la surface
						$range = ($data2["surface"] * 0.25);

						//on approxim le prix
						$range2 = ($data2["prix_week"] * 0.25);

						if($data2["id_type"] == $type_bien["id"])
						{
							if(($data2["surface"] >= ($surface - $range)) && ($data2["surface"] <= ($surface + $range)))
							{
								if(($data2["prix_week"] >= ($prix - $range2)) && ($data2["prix_week"] <= ($prix + $range2)))
								{
									$ret_table[$i] = $data2;
									$i++;
								}
								else
								{
									$error = "Plusieurs biens de ce type et surface dans $ville, mais pas ce tarifs";
								}
							}
							else
							{
								$error = "Plusieurs biens de ce type dans $ville, mais pas ce surface";
							}
						}
						else
						{
							$error = "Aucun bien ce type dans $ville";
						}
					}
				}
				else
				{
					$error = "Pas de résultat dans cette ville";
				}
				
			}

		}
		else
		{
			$error = "Aucune ville correspond!";
		}
	}

	//Recup type_bien
	$query = "SELECT * FROM type_bien";
	$types = mysqli_query($bdd,$query);
	
	//Recup pays
	$query = "SELECT * FROM pays";
	$pays = mysqli_query($bdd,$query);
	
	include_once("freebed-search.html");
?>